package com.poisonh.unifiedauth.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dao.UserinfoDaoImpl;
import com.poisonh.unifiedauth.model.UserInfoModel;
import com.poisonh.unifiedauth.utils.ActivityStack;
import com.poisonh.unifiedauth.utils.CommonUtils;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;

/**
 * 更换手机号
 * Created by PoisonH on 2016/6/28.
 */
public class ChangePhoneActivity extends BaseActivity implements View.OnClickListener
{
    //手机号码输入框
    private EditText mChangePhoneInputPhone;
    //手机验证码输入框
    private EditText mChangePhoneInputPhoneCode;
    //验证码发送按钮
    private Button mBtnSendCode;
    //更改手机号码确认按钮
    private Button mBtnSure;
    //手机号码
    private String mStrPhone;
    //手机验证码
    private String mStrSmsCode;

    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_changephone);
        mStrPhone = getIntent().getStringExtra("PHONE");
        initTitleView();
        initView();

    }

    @Override
    protected void initView()
    {
        setTitleTxt("更换手机");
        mRightBtn.setVisibility(View.GONE);
        mLeftBtn.setOnClickListener(this);

        mChangePhoneInputPhone = (EditText) findViewById(R.id.changephone_phone);
        mChangePhoneInputPhone.setText(mStrPhone);
        mChangePhoneInputPhoneCode = (EditText) findViewById(R.id.changephone_input_phonecode);
        mBtnSendCode = (Button) findViewById(R.id.changephone_send_phonecode);
        mBtnSure = (Button) findViewById(R.id.changephone_sure);
        mChangePhoneInputPhoneCode.addTextChangedListener(mEditTextCodeWatcher);
        mBtnSendCode.setOnClickListener(this);
        mBtnSure.setOnClickListener(this);
        sendSmsCode(mStrPhone);
        mBtnSendCode.setEnabled(false);
        CommonUtils.CountdownTime(mBtnSendCode);
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ib_left_btn:
                finish();
                break;
            case R.id.changephone_send_phonecode:
                mStrPhone = mChangePhoneInputPhone.getText().toString();
                if (mStrPhone.trim().length() != 11)
                {
                    ToastUtils.showToast(ChangePhoneActivity.this, getString(R.string.sure_input_11_phone));
                } else
                {
                    sendSmsCode(mStrPhone);
                    mBtnSendCode.setEnabled(false);
                }
                break;
            case R.id.changephone_sure:
                mStrSmsCode = mChangePhoneInputPhoneCode.getText().toString();
                if (TextUtils.isEmpty(mStrSmsCode) && mStrSmsCode.length() != 6)
                {
                    ToastUtils.showToast(this, "请输入6位验证码");
                } else
                {
                    HttpParams params = new HttpParams();
                    params.put("userId", mStrUserId);
                    params.put("token", mStrUserToken);
                    params.put("phone", mStrPhone);
                    params.put("msgCode", mStrSmsCode);
                    changePhone(params);
                }
                break;
        }
    }

    /**
     * 发送短信验证码
     */
    private void sendSmsCode(String mStrPhone)
    {
        HttpParams params = new HttpParams();
        params.put("phone", mStrPhone);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.SEND_MESSAGE, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                CommonUtils.CountdownTime(mBtnSendCode);
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(ChangePhoneActivity.this, failReason);
                mBtnSendCode.setText(R.string.login_tips_btn_phonecode);
                mBtnSendCode.setEnabled(true);
            }
        });
    }

    /**
     * 发送短信验证码
     */
    private void changePhone(HttpParams params)
    {
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.CHANGEPHONE, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                ToastUtils.showToast(ChangePhoneActivity.this, "更换手机成功");
                // startActivity(new Intent(ChangePhoneActivity.this, LoginActivity.class));
                // ActivityStack.getAppManager().exit();
                //ConstantUitls.mStrPhone = mStrPhone;
                if (mStrUserName == null)
                {
                    sendChangeHeadBR(mStrPhone);
                }
                ActivityStack.getAppManager().finishActivity(ShowOldPhoneActivity.class);
                ActivityStack.getAppManager().finishActivity(InputNewPhoneActivity.class);
                finish();
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(ChangePhoneActivity.this, failReason);
            }
        });
    }

    /**
     * 验证码输入监听
     */
    TextWatcher mEditTextCodeWatcher = new TextWatcher()
    {
        private CharSequence temp;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
        }

        @Override
        public void afterTextChanged(Editable s)
        {
            //验证码6位隐藏键盘
            if (temp.length() == 6)
            {
                mBtnSure.setEnabled(true);
                mBtnSure.setBackground(getResources().getDrawable(R.drawable.shape_settingmyinfo_btn_bg));
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mChangePhoneInputPhoneCode.getWindowToken(), 0);
            } else
            {
                mBtnSure.setEnabled(false);
                mBtnSure.setBackground(getResources().getDrawable(R.drawable.shape_settingmyinfo_btn_bg_));
            }
        }
    };

    /**
     * 更改数据库，并且发送更改手机号的广播
     */
    private void sendChangeHeadBR(String phone)
    {
        try
        {
            //根据id查询用户
            UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(ChangePhoneActivity.this);
            UserInfoModel model = mUserinfoDaoImpl.queryReturnOne(mStrUserId);
            model.setmStrPhone(phone);
            mUserinfoDaoImpl.commit();
            Intent mInent = new Intent("HEAD_CHANGE");
            this.sendBroadcast(mInent);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
